import fs from 'fs';
import path from 'path';

/**
 * 获取客户端请求的应用名
 *
 * @param url 请求资源路径
 */
export function getAppName (url: string): string {
    return url.split('/')[1];
}

/**
 * 判断客户端请求的应用是否存在
 *
 * @param appName        请求的应用名
 * @param webappsDirPath 存放应用的目录路径
 */
export function hasApp (appName: string, webappsDirPath: string): boolean {
    return fs.readdirSync(webappsDirPath, { withFileTypes: true }).some(file => {
        return file.isDirectory() && file.name === appName;
    });
}

/**
 * 获取资源请求的根路径
 *
 * @param hasApp         客户端请求的应用是否存在
 * @param webappsDirPath 存放应用的目录路径
 * @param defaultAppName 默认的应用名
 */
export function getRootPath (hasApp: boolean, webappsDirPath: string, defaultAppName: string): string {
    return hasApp ? webappsDirPath : path.join(webappsDirPath, defaultAppName);
}

/**
 * 获取请求资源的路径
 *
 * @param rootPath 资源请求的根路径
 * @param urls     请求的资源路径
 */
export function getAssetPath (rootPath: string, ...urls: Array<string>): string {
    return path.join(rootPath, ...urls);
}

/**
 * 判断请求资源是否带有后缀
 *
 * @param url 请求资源路径
 */
export function hasSuffix (url: string): boolean {
    const urlSplit = url.split('/');
    const lastIndex = urlSplit.length - 1;
    const assetName = urlSplit[lastIndex];
    const hasSuffix = assetName.lastIndexOf('.');

    return hasSuffix !== -1;
}

/**
 * 获取请求资源后缀
 *
 * @param url 请求资源路径
 */
export function getSuffix (url: string): string | undefined {
    const urlSplit = url.split('/');
    const lastIndex = urlSplit.length - 1;
    const assetName = urlSplit[lastIndex];
    const hasSuffix = assetName.lastIndexOf('.');

    return hasSuffix !== -1 ? assetName.slice(hasSuffix) : undefined;
}

/**
 * 去除资源后缀
 *
 * @param url 请求资源URL
 */
export function removeSuffix (url: string): string {
    const urlSplit = url.split('/');
    const lastIndex = urlSplit.length - 1;
    const assetName = urlSplit[lastIndex];
    const hasSuffix = assetName.lastIndexOf('.');

    return hasSuffix !== -1 ? urlSplit.slice(0, urlSplit.length - 1).join('/') + `/${assetName.slice(0, hasSuffix)}` : url;
}
